#!/usr/bin/env python3
"""
初始化数据脚本
"""
import sys
import os
import asyncio
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from app.core.database import init_db, get_db_context
from app.models.release import (
    Release, ReleaseStep, DeploymentConfig,
    ReleaseStatus, DeploymentStrategy, Environment
)
from app.core.config import current_settings

logger = logging.getLogger(__name__)


async def init_sample_data():
    """初始化示例数据"""
    try:
        print("开始初始化示例数据...")
        
        with get_db_context() as db:
            # 创建示例部署配置
            await create_sample_deployment_configs(db)
            
            # 创建示例发布记录
            await create_sample_releases(db)
            
            print("示例数据初始化完成！")
            
    except Exception as e:
        print(f"初始化数据失败: {e}")
        sys.exit(1)


async def create_sample_deployment_configs(db):
    """创建示例部署配置"""
    configs = [
        {
            "name": "生产环境蓝绿部署",
            "environment": Environment.PRODUCTION,
            "strategy": DeploymentStrategy.BLUE_GREEN,
            "config": {
                "blue_environment": "blue-prod",
                "green_environment": "green-prod",
                "load_balancer": "nginx-prod",
                "health_check_endpoints": [
                    "/health",
                    "/api/health"
                ]
            },
            "description": "生产环境蓝绿部署配置",
            "version": "1.0.0"
        },
        {
            "name": "测试环境金丝雀发布",
            "environment": Environment.TESTING,
            "strategy": DeploymentStrategy.CANARY,
            "config": {
                "canary_percentage": 10,
                "evaluation_period": 300,
                "success_threshold": 95,
                "health_check_interval": 30
            },
            "description": "测试环境金丝雀发布配置",
            "version": "1.0.0"
        },
        {
            "name": "开发环境滚动更新",
            "environment": Environment.DEVELOPMENT,
            "strategy": DeploymentStrategy.ROLLING,
            "config": {
                "max_unavailable": 1,
                "max_surge": 1,
                "min_ready_seconds": 60,
                "progress_deadline_seconds": 600
            },
            "description": "开发环境滚动更新配置",
            "version": "1.0.0"
        }
    ]
    
    for config_data in configs:
        existing = db.query(DeploymentConfig).filter(
            DeploymentConfig.name == config_data["name"]
        ).first()
        
        if not existing:
            config = DeploymentConfig(**config_data)
            db.add(config)
            print(f"创建部署配置: {config_data['name']}")
    
    db.commit()


async def create_sample_releases(db):
    """创建示例发布记录"""
    releases = [
        {
            "version": "v1.0.0",
            "description": "初始版本发布",
            "environment": Environment.PRODUCTION,
            "strategy": DeploymentStrategy.BLUE_GREEN,
            "status": ReleaseStatus.SUCCESS,
            "deployed_by": "admin",
            "config": {
                "blue_environment": "blue-prod-v1.0.0",
                "green_environment": "green-prod-v1.0.0"
            }
        },
        {
            "version": "v1.1.0",
            "description": "功能增强版本",
            "environment": Environment.PRODUCTION,
            "strategy": DeploymentStrategy.CANARY,
            "status": ReleaseStatus.SUCCESS,
            "deployed_by": "admin",
            "config": {
                "canary_percentage": 20,
                "evaluation_period": 600
            }
        },
        {
            "version": "v1.2.0",
            "description": "性能优化版本",
            "environment": Environment.PRODUCTION,
            "strategy": DeploymentStrategy.ROLLING,
            "status": ReleaseStatus.PENDING,
            "deployed_by": "developer",
            "config": {
                "max_unavailable": 0,
                "max_surge": 2
            }
        }
    ]
    
    for release_data in releases:
        existing = db.query(Release).filter(
            Release.version == release_data["version"],
            Release.environment == release_data["environment"]
        ).first()
        
        if not existing:
            release = Release(**release_data)
            db.add(release)
            db.flush()  # 获取ID
            
            # 创建发布步骤
            await create_release_steps(db, release)
            
            print(f"创建发布记录: {release_data['version']}")
    
    db.commit()


async def create_release_steps(db, release: Release):
    """创建发布步骤"""
    if release.strategy == DeploymentStrategy.BLUE_GREEN:
        steps = [
            {"name": "准备蓝绿环境", "description": "准备蓝绿部署环境", "order": 1},
            {"name": "部署到绿环境", "description": "将新版本部署到绿环境", "order": 2},
            {"name": "健康检查", "description": "检查绿环境服务状态", "order": 3},
            {"name": "切换流量", "description": "将流量从蓝环境切换到绿环境", "order": 4},
            {"name": "清理蓝环境", "description": "清理旧的蓝环境", "order": 5}
        ]
    elif release.strategy == DeploymentStrategy.CANARY:
        steps = [
            {"name": "准备金丝雀环境", "description": "准备金丝雀发布环境", "order": 1},
            {"name": "部署金丝雀版本", "description": "部署新版本到金丝雀环境", "order": 2},
            {"name": "健康检查", "description": "检查金丝雀环境状态", "order": 3},
            {"name": "逐步扩大流量", "description": "逐步增加金丝雀版本的流量", "order": 4},
            {"name": "全量发布", "description": "完成全量发布", "order": 5}
        ]
    else:  # Rolling
        steps = [
            {"name": "准备滚动更新", "description": "准备滚动更新环境", "order": 1},
            {"name": "逐步更新实例", "description": "逐个更新服务实例", "order": 2},
            {"name": "健康检查", "description": "检查更新后的实例状态", "order": 3},
            {"name": "验证服务", "description": "验证服务功能正常", "order": 4},
            {"name": "完成更新", "description": "完成所有实例更新", "order": 5}
        ]
    
    for step_data in steps:
        step = ReleaseStep(
            release_id=release.id,
            step_name=step_data["name"],
            step_order=step_data["order"],
            description=step_data["description"],
            status=ReleaseStatus.SUCCESS if release.status == ReleaseStatus.SUCCESS else ReleaseStatus.PENDING
        )
        db.add(step)


async def main():
    """主函数"""
    print("SaaS平台发布与回滚系统 - 数据初始化")
    print("=" * 50)
    
    # 检查环境
    print(f"当前环境: {current_settings.ENVIRONMENT}")
    print(f"数据库: {current_settings.DATABASE_URL}")
    
    # 初始化数据库
    print("\n初始化数据库...")
    init_db()
    
    # 初始化示例数据
    await init_sample_data()
    
    print("\n初始化完成！")
    print("您可以通过以下方式访问系统:")
    print("- API文档: http://localhost:8000/docs")
    print("- 健康检查: http://localhost:8000/health")


if __name__ == "__main__":
    import logging
    logging.basicConfig(level=logging.INFO)
    asyncio.run(main())
